<template>
  <div class="permission">
    <el-card>
      <div class="add">
        <el-button type="primary" @click="add('0',1)">添加菜单</el-button>
      </div>
      <!-- 表格中渲染树形数据结构要有两个条件1\树形数据结构;
      2\每一条数据都有相对应的id并且再el-table中用row-key中渲染出来 -->
      <el-table :data="list" row-key="id">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作" width="500px">
          <template v-slot="{row}">
            <el-button v-if="row.type===1" type="text" @click="add(row.id,1)">添加页面权限点</el-button>
            <el-button v-if="row.type===1" type="text" @click="add(row.id,2)">添加按钮权限点</el-button>
            <el-button type="text" @click="edit(row)">查看api权限点</el-button>
            <el-button type="text">查看</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <Add ref="add" v-model="isShow" @getPermissionList="getPermissionList" />
  </div>
</template>

<script>
import { syspermission, syspermissionDelete } from '@/api/permission.js'
// 导入添加组件
import Add from './components/add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      list: [{}],
      isShow: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 点击修改权限按钮
    edit(row) {
      this.isShow = true
      this.$refs.add.mode = 'edit'
      // 深拷贝row值赋值给add组件的form变量,实现数据的回显
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },
    // 点击删除按钮删除当前行的权限
    del(id) {
      this.$confirm('您确定删除这个权限嘛', '提示').then(async() => {
        await syspermissionDelete(id)
        // 提示删除成功
        this.$message.success('删除成功')
        // 刷新页面
        this.getPermissionList()
      }).catch(() => {})
    },
    // 点击添加权限按钮添加权限
    add(pid, type) {
      this.$refs.add.mode = 'add'
      console.log(pid)
      this.isShow = true
      // 把add组件的值type,pid给传给add添加组件区分我点击了哪一个
      this.$refs.add.form.pid = pid
      this.$refs.add.form.type = type
    },
    async getPermissionList() {
      const res = await syspermission()
      this.list = res.data
      this.list = this.createTreeData(this.list, '0')
      // console.log(this.list)
      // console.log(res)
    },
    // 生成树形数据结构数据
    createTreeData(arr, pid) {
      return arr.filter(item => {
        // 把第一层父节点渲染出来
        // item.children表示把每个父节点的孩子节点找到
        if (item.pid === pid) {
          item.children = this.createTreeData(arr, item.id)
          return true
        }
      })
    }
  }

}
</script>

<style lang='scss' scoped>
.permission{
  padding: 15px;
  .add{
    text-align: right;
    margin-bottom: 30px;
  }
}
</style>
